const { updateUser } = require("../../../utils/request");
const config = require("../../../utils/config");

Page({
  data: {
    userInfo: {
      avatarUrl: "/static/icons/default-avatar.png",
      nickName: "",
    },
    oldNickName: "",
  },

  onLoad() {
    this.loadUserData();
  },

  loadUserData() {
    const userInfo = wx.getStorageSync("userInfo") || {
      avatarUrl: "/static/icons/default-avatar.png",
      nickName: "Nickname not set",
    };
    // 仅在展示时拼接 `config.ImageURL`
    if (userInfo.avatarUrl && !userInfo.avatarUrl.startsWith("/static/")) {
      userInfo.avatarUrl = config.ImageURL + userInfo.avatarUrl;
    }
    this.setData({ 
      userInfo,
      oldNickName: userInfo.nickName 
    });
  },

  // 选择头像
  changeAvatar() {
    wx.chooseMedia({
      count: 1,
      mediaType: ["image"],
      sourceType: ["album", "camera"],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        this.uploadImage(tempFilePath);
      },
      fail: (err) => {
        console.log("头像更换失败", err);
      },
    });
  },

  // 上传图片到服务器
  uploadImage(filePath) {
    const token = wx.getStorageSync("token");
    wx.uploadFile({
      url: `${config.baseURL}/art-resource/uploadUserAvatarImage`, // 服务器上传接口
      filePath: filePath,
      name: "file", // 必须与后端 `@RequestParam("file")` 名称匹配
      header: {
        "Content-Type": "multipart/form-data",
        Authorization: token, // 设置 Authorization 头部
      },
      success: (res) => {
        try {
          const parsedData = JSON.parse(res.data);
          if (parsedData && parsedData.data) {
            console.log("上传成功的图片路径：" + parsedData.data);
            this.setData({
              "userInfo.avatarUrl": config.ImageURL + parsedData.data, // 更新头像地址
            });
          } else {
            wx.showToast({
              title: "Upload Failed",
              icon: "none",
            });
          }
        } catch (error) {
          console.log("JSON 解析失败", error);
          wx.showToast({
            title: "Upload Failed",
            icon: "none",
          });
        }
      },
      fail: (err) => {
        console.log("上传失败", err);
        wx.showToast({
          title: "Upload Failed",
          icon: "none",
        });
      },
    });
  },

  // 修改昵称
  onNicknameChange(e) {
    const nickName = e.detail.value;
    let nickNameError = "";

    // 检查昵称长度
    if (nickName.length > 30) {
      nickNameError = "Nickname cannot exceed 30 characters";
    }

    this.setData({
      "userInfo.nickName": nickName,
      nickNameError,
    });
  },

  // 保存个人信息
  saveProfile() {
    const nickName = this.data.userInfo.nickName.trim();

    // 昵称不能为空
    if (!nickName) {
      wx.showToast({
        title: "Nickname is required",
        icon: "none",
      });
      return;
    }

    // 检查昵称长度
    if (nickName.length > 30) {
      wx.showToast({
        title: "Nickname cannot exceed 30 characters",
        icon: "none",
      });
      return;
    }

    // 去掉 `config.ImageURL`，只存储相对路径
    let avatarUrl = this.data.userInfo.avatarUrl.replace(config.ImageURL, "");

    // 保存修改的数据
    updateUser({ nickName, avatarUrl })
      .then((res) => {
        if (res.code === "00000") {
          wx.showToast({
            title: "Save Successful",
            icon: "success",
          });

          // 更新本地存储
          let userInfo = { ...this.data.userInfo, avatarUrl };
          wx.setStorageSync("userInfo", userInfo);

          setTimeout(() => {
            wx.navigateBack();
          }, 1000);
        } else {
          wx.showToast({
            title: "Save Failed",
            icon: "none",
          });
        }
      })
      .catch((err) => {
        console.log("保存失败", err);
        wx.showToast({
          title: "Save Failed",
          icon: "none",
        });
      });
  },
});
